/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

import dao.Dao;
import entidades.Usuario;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.Date;
import java.util.List;
import java.util.Map;
import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 *
 * @author aluno
 */
@WebServlet(name = "ServletCadastroUsuario", urlPatterns = {"/ServletCadastroUsuario"})
public class ServletCadastroUsuario extends HttpServlet {

    /** 
     * Processes requests for both HTTP <code>GET</code> and <code>POST</code> methods.
     * @param request servlet request
     * @param response servlet response
     * @throws ServletException if a servlet-specific error occurs
     * @throws IOException if an I/O error occurs
     */
    protected void processRequest(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        response.setContentType("text/html;charset=UTF-8");
        PrintWriter out = response.getWriter();
        try {
            /* TODO output your page here
            out.println("<html>");
            out.println("<head>");
            out.println("<title>Servlet ServletCadastroUsuario</title>");  
            out.println("</head>");
            out.println("<body>");
            out.println("<h1>Servlet ServletCadastroUsuario at " + request.getContextPath () + "</h1>");
            out.println("</body>");
            out.println("</html>");
             */
        } finally {
            out.close();
        }
    }

    // <editor-fold defaultstate="collapsed" desc="HttpServlet methods. Click on the + sign on the left to edit the code.">
    /** 
     * Handles the HTTP <code>GET</code> method.
     * @param request servlet request
     * @param response servlet response
     * @throws ServletException if a servlet-specific error occurs
     * @throws IOException if an I/O error occurs
     */
    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        int id = Integer.parseInt(request.getParameter("id"));
                Dao<Usuario> dao = new Dao<Usuario>(Usuario.class);
        Usuario u = dao.get(id);
        u.setContaConfirmada(true);
        dao.update(u);
        response.sendRedirect("contaConfirmada.jsp");
        
    }
    /** 
     * Handles the HTTP <code>POST</code> method.
     * @param request servlet request
     * @param response servlet response
     * @throws ServletException if a servlet-specific error occurs
     * @throws IOException if an I/O error occurs
     */
    public final String dir = "/files/";

    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        Upload upload = new Upload(getServletContext().getRealPath(dir));

        // Retorna um list com todos os componentes de uma requisição
        List list1 = upload.processRequest(request);

        // Neste Map você obteve todos os campos do formulário.
        Map<String, String> map = upload.getFormValues(list1);
        String foto = Global.getNomeFoto();
        Global.setNomeFoto("");
        String ano = map.get("ano_");
        System.out.println(map.get("ano"));
        String dia = map.get("dia_");
        String mes = map.get("mes_");
        String email = map.get("email");
        String senha = map.get("senha");
        String nome = map.get("nome");
        //case{

        //}
        String n = ano + "/" + mes + "/" + dia;
        Date nasc = Util.stringToDate(n);// falta código do silvano de String to date e datetostring
        foto = map.get("foto");
        System.out.println(nasc);

        //yyyy/mm/dd

        Usuario user = new Usuario();
        user.setCaminhoFoto(foto);
        user.setData_nasc(nasc);
        user.setEmail(email);
        user.setSenha(senha);
        user.setNome(nome);


        Dao<Usuario> dao = new Dao<Usuario>(Usuario.class);
        List<Usuario> list = dao.list();
        boolean igual = false;
        for (Usuario usuario : list) {
            if (usuario.getEmail().equals(email)) {
                igual = true;

            }

        }
        if (!igual) {
            dao.insert(user);

            EmailSender emailSender = new EmailSender();
            emailSender.setEmailTo(email);
            emailSender.setEmailSubject("Com-Argo - Confirmação de Cadastro");
            emailSender.setEmailMessage("Cadastro realizado com sucesso."
                    + " Porém, para poder usufruir de sua conta, é necessária"
                    + " a confirmação de seu cadastro. Para confirmar sua conta, clique"
                    + "no link a seguir.               "
                    + "http://localhost:8084/ERMusicZone/ServletCadastroUsuario?id=" + user.getId());
            emailSender.send();


            RequestDispatcher rd = request.getRequestDispatcher("Usuario.jsp");
            rd.forward(request, response);
        } else {
            RequestDispatcher rd = request.getRequestDispatcher("cadastroUsuario.jsp");
            rd.forward(request, response);
        }



    }
    /** 
     * Returns a short description of the servlet.
     * @return a String containing servlet description
     */
}
